package net.hn.hnms.biz.mine.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import net.hn.hnms.biz.mine.controller.OtherSystemApi;
import net.hn.hnms.biz.mine.domain.dto.MiningSystemRunTimeDayDto;
import net.hn.hnms.biz.mine.domain.OtherApiURL;
import net.hn.hnms.biz.mine.domain.dto.MiningSystemRunTimeMinuteDetailDto;
import net.hn.hnms.biz.mine.service.OtherSystemApiService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OtherSystemApiServiceImpl implements OtherSystemApiService {
    /**
     * signature签证
     * @param appKey
     * @param appSecret
     * @param timestamp
     * @return
     */
    @Override
    public String getSignature(String appKey, String appSecret, String timestamp) {
        if (StringUtils.isBlank(timestamp)) {
            timestamp=String.valueOf(System.currentTimeMillis());
        }
        if (StringUtils.isBlank(appKey)) {
            appKey = OtherApiURL.APP_KEY;
        }
        //获取签名 appKey + appSecret + timestamp 拼接后采用SHA-256加密方式
        String signature = appKey + appSecret + timestamp;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(signature.getBytes("UTF-8"));

            // 将 byte 数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
             signature = hexString.toString();
            System.out.println("Signature: " + signature);
            return signature;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取扎煤-采煤每日运行状态总时长
     * @param ip
     * @param signature
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public List<MiningSystemRunTimeDayDto> getMiningSystemRunTimeDay(String ip, String signature,String timestamp, Date startDate, Date endDate) {
        //判断签名是否为空
        if (StringUtils.isBlank(signature)) {
            throw new HuaNengException(Constants.FAIL, "signature不能为空");
        }
        //判断时间戳是否为空
        if (StringUtils.isBlank(timestamp)) {
            timestamp = String.valueOf(System.currentTimeMillis());
        }
        // 创建 SimpleDateFormat 对象，指定日期时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 使用 SimpleDateFormat 格式化 Date 对象为字符串
        String startDateStr = sdf.format(startDate);
        String endDateStr = sdf.format(endDate);

        //获取 采煤每日运行总时长请求路径
        String miningRuntimeDayURl = OtherApiURL.MINING_RUNTIME_DAY;
        //获取appkey
        String appKey = OtherApiURL.APP_KEY;
        String url = ip+miningRuntimeDayURl + "?appKey=" + appKey + "&signature=" + signature + "&timestamp=" + timestamp;
        // 判断是否需要追加 startDate 参数
        if (!startDateStr.isEmpty()) {
            url += "&startDate=" + URLEncoder.encode(startDateStr);
        }

        // 判断是否需要追加 endDate 参数
        if (!endDateStr.isEmpty()) {
            url += "&endDate=" + URLEncoder.encode(endDateStr);
        }
        //返回数据集合
        List<MiningSystemRunTimeDayDto> miningSystemRunTimeDayDtos = null;
        //发送get请求
        try {
             miningSystemRunTimeDayDtos = OtherSystemApi.sendGetRequest(url, "", new TypeReference<List<MiningSystemRunTimeDayDto>>() {});
            if (miningSystemRunTimeDayDtos.isEmpty()) {
                return new ArrayList<>();
            }
        } catch (IOException e) {
            System.out.println("获取扎煤-采煤每日运行总时长失败：" + url);
            throw new RuntimeException(e);
        }
        return miningSystemRunTimeDayDtos;
    }

    /**
     * 获取扎煤-采煤每分钟运行状态明细
     * @param ip
     * @param signature
     * @param timestamp
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public List<MiningSystemRunTimeMinuteDetailDto> getMiningSystemRunTimeMinuteDetail(String ip, String signature, String timestamp, Date startDate, Date endDate) {
        //判断签名是否为空
        if (StringUtils.isBlank(signature)) {
            throw new HuaNengException(Constants.FAIL, "signature不能为空");
        }
        //判断时间戳是否为空
        if (StringUtils.isBlank(timestamp)) {
            timestamp = String.valueOf(System.currentTimeMillis());
        }
        // 创建 SimpleDateFormat 对象，指定日期时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 使用 SimpleDateFormat 格式化 Date 对象为字符串
        String startDateStr = sdf.format(startDate);
        String endDateStr = sdf.format(endDate);

        //获取 采煤每分钟运行时长请求路径
        String miningRuntimeMinuteURL = OtherApiURL.MINING_RUNTIME_MINUTE;
        //获取appkey
        String appKey = OtherApiURL.APP_KEY;
        String url = ip+miningRuntimeMinuteURL + "?appKey=" + appKey + "&signature=" + signature + "&timestamp=" + timestamp;
        // 判断是否需要追加 startDate 参数
        if (!startDateStr.isEmpty()) {
            url += "&startDate=" + URLEncoder.encode(startDateStr);
        }

        // 判断是否需要追加 endDate 参数
        if (!endDateStr.isEmpty()) {
            url += "&endDate=" + URLEncoder.encode(endDateStr);
        }
        //返回数据集合
        List<MiningSystemRunTimeMinuteDetailDto> miningSystemRunTimeMinuteDetailDtos = null;
        //发送get请求
        try {
            miningSystemRunTimeMinuteDetailDtos = OtherSystemApi.sendGetRequest(url, "", new TypeReference<List<MiningSystemRunTimeMinuteDetailDto>>() {});
            if (miningSystemRunTimeMinuteDetailDtos.isEmpty()) {
                return new ArrayList<>();
            }
        } catch (IOException e) {
            System.out.println("获取扎煤-采煤每日运行总时长失败：" + url);
            throw new RuntimeException(e);
        }
        return miningSystemRunTimeMinuteDetailDtos;
    }
}
